import 'dart:convert';

import 'package:worker_manager/worker_manager.dart';

/// 异步json
class Json {
  Json._();

  /// 异步解析json字符串
  static Future<dynamic> decode(
    String source, {
    Object? Function(Object? key, Object? value)? reviver,
    bool? isErrorBackOriginal,
    dynamic defaultValue,
  }) {
    return workerManager.execute(() {
      try {
        return jsonDecode(source, reviver: reviver);
      } catch (e) {
        if (isErrorBackOriginal == true) {
          return source;
        } else {
          return defaultValue;
        }
      }
    }).future;
  }

  /// 异步解析json字符串
  static Future<dynamic> decodeBytes(
    List<int> codeUnits, {
    Object? Function(Object? key, Object? value)? reviver,
    bool? isErrorBackOriginal,
    dynamic defaultValue,
  }) {
    return workerManager.execute(() {
      try {
        final text = utf8.decode(codeUnits, allowMalformed: true);
        return jsonDecode(text, reviver: reviver);
      } catch (e) {
        if (isErrorBackOriginal == true) {
          return codeUnits;
        } else {
          return defaultValue;
        }
      }
    }).future;
  }

  /// 异步编码对象为json字符串
  static Future<String> encode(Object? value,
      {Object? Function(Object? nonEncodable)? toEncodable}) {
    return workerManager
        .execute(() => jsonEncode(value, toEncodable: toEncodable))
        .future;
  }
}
